/**
 * Created by Administrator on 2017/6/28.
 */
/**
 * Created by Administrator on 2017/6/12.
 */
var Promise = require('bluebird');
var Category = Promise.promisifyAll(require('../models/category'));

//category列表页
exports.list = function *(req, res) {
  var _categories = yield Category.findAll();
  res.render('category/categoryList', {
    title: 'category列表页',
    categories: _categories
  });
}

//category录入页
exports.add = function *(req, res) {
  res.render('category/categoryAdd', {
    title: 'category录入页'
  });
}

//category详情页
exports.detail = function *(req, res) {
  var id = req.params.id;
  var page = req.query.page;
  var pageSize = 8;
  var _cate = yield Category.findById(id);
  var totalPages = Math.ceil(_cate.movies.length / pageSize);
  var _category = yield Category.findByIdAndPages(id, pageSize, page);
  res.render('category/categoryDetail', {
    title: 'category详情页',
    category: _category,
    totalPages: totalPages,
    currentPage: page
  });
}

//category进行录入
exports.create = function *(req, res) {
  var category = req.body;
  category.time = Date.now();
  var _category = yield Category.findOne({name: category.name});
  if (_category) {
    res.send('分类已存在!');
  } else {
    var newCategory = new Category(category);
    var _category = yield newCategory.save();
    if (_category) {
      res.redirect('/category/add');
    }
  }
}

//category进行删除
exports.del = function *(req, res) {
  var id = req.body.id;
  var commandResult = yield Category.remove({_id: id});
  if (commandResult.result.n == 1) {
    res.send('true');
  } else {
    res.send('false');
  }
}

//category修改movies
exports.updateMovies = function *(req, res) {
  var data = req.body;
  var _category = yield Category.findOne({_id: data.cateId});
  if (data.add == 'true') { //新增
    _category.movies.push(data.movieId);
  } else {  //删除
    _category.movies.removeByValue(data.movieId);
  }
  yield Category.update({_id: data.cateId}, _category);
}

Array.prototype.removeByValue = function(val) {
  for(var i=0; i<this.length; i++) {
    if(this[i] == val) {
      this.splice(i, 1);
      break;
    }
  }
}
